package io.github.qifan777.server.deliver.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import io.github.qifan777.server.deliver.entity.Deliver;
import io.github.qifan777.server.deliver.entity.dto.DeliverInput;
import io.github.qifan777.server.deliver.entity.dto.DeliverSpec;
import io.github.qifan777.server.deliver.repository.DeliverRepository;
import io.github.qifan777.server.dict.model.DictConstants;
import io.github.qifan777.server.infrastructure.model.QueryRequest;
import io.github.qifan777.server.role.entity.Role;
import io.github.qifan777.server.role.repository.RoleRepository;
import io.github.qifan777.server.user.root.entity.UserRoleRelDraft;
import io.github.qifan777.server.user.root.repository.UserRoleRelRepository;
import io.qifan.infrastructure.common.exception.BusinessException;
import lombok.AllArgsConstructor;
import lombok.val;
import org.babyfish.jimmer.client.FetchBy;
import org.babyfish.jimmer.client.meta.DefaultFetcherOwner;
import org.springframework.data.domain.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("admin/deliver")
@AllArgsConstructor
@DefaultFetcherOwner(DeliverRepository.class)
@SaCheckPermission("/deliver")
@Transactional
public class DeliverForAdminController {
    private final DeliverRepository deliverRepository;
    private final RoleRepository roleRepository;
    private final UserRoleRelRepository userRoleRelRepository;

    @GetMapping("{id}")
    public @FetchBy(value = "COMPLEX_FETCHER_FOR_ADMIN") Deliver findById(@PathVariable String id) {
        return deliverRepository.findById(id, DeliverRepository.COMPLEX_FETCHER_FOR_ADMIN).orElseThrow(() -> new BusinessException("数据不存在"));
    }

    @PostMapping("query")
    public Page<@FetchBy(value = "COMPLEX_FETCHER_FOR_ADMIN") Deliver> query(@RequestBody QueryRequest<DeliverSpec> queryRequest) {
        return deliverRepository.findPage(queryRequest, DeliverRepository.COMPLEX_FETCHER_FOR_ADMIN);
    }

    public String insert(DeliverInput input) {
        return deliverRepository.insert(input.toEntity()).id();
    }

    public String update(DeliverInput input) {
        if (input.getStatus().equals(DictConstants.ApproveStatus.PASS)){
            val deliver = deliverRepository.findById(input.getId(), DeliverRepository.COMPLEX_FETCHER_FOR_FRONT)
                    .orElseThrow();
            Role role = roleRepository.findRoleByName("接单者").orElseThrow();
            userRoleRelRepository.save(UserRoleRelDraft.$.produce(draft -> {
                draft.setUserId(deliver.creator().id())
                        .setRoleId(role.id());
            }));
        }
        return deliverRepository.save(input.toEntity()).id();
    }

    @PostMapping("save")
    public String save(@RequestBody @Validated DeliverInput input) {
        return StringUtils.hasText(input.getId()) ? update(input) : insert(input);
    }

    @DeleteMapping
    public Boolean delete(@RequestBody List<String> ids) {
        deliverRepository.deleteAllById(ids);
        return true;
    }
}